package com.feihong.yw189.activity.yonghuzhongxin.wodexiaoxi;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.adapter.MsgAdapter;
import com.feihong.yw189.app.App;
import com.feihong.yw189.global.RequestTools;
import com.feihong.yw189.http.Host;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.User.message.SystemMessageListModel;
import com.feihong.yw189.utils.UserLoginInfo;
import com.holenzhou.pullrecyclerview.PullRecyclerView;
import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import org.xutils.common.Callback;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class SysteMessageListActivity extends BaseActivity {

    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.iv_confirm)
    TextView ivConfirm;
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.takePlc)
    View takePlc;
    @BindView(R.id.pull_recycler_view)
    PullRecyclerView mPullRecyclerView;

    private MsgAdapter mAdapter;
    private int pageGlobal = 2;
    private Unbinder unbinder;
    /**
     * 界面总消息数量
     */
    private int mDataSize = 0;

    @BindView(R.id.connect_net_error_layout)
    LinearLayout mNetErrorLayout;
    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.null_data_layout_txt)
    TextView mNullDataWarningTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_list);
        unbinder = ButterKnife.bind(this);

        initView();
        bindData();
    }

    @Override
    public void setTheme() {

    }

    public void initView() {
        setBackButtonFinish();
        setPageTitle("系统消息");
        ivLin.setVisibility(View.GONE);
    }

    public void bindData() {

        //初始数据
        // 设置LayoutManager（这里需要使用lib里面提供的XLinearLayoutManager或XGridLayoutManager，默认为XLinearLayoutManager）
        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        // 创建adapter，adapter的使用方法看后面
        mAdapter = new MsgAdapter(this);
        mAdapter.setOnItemClickListener(msgInfo -> {
            Intent intent = new Intent(this,SystemNoticeDetailActivity.class);
            intent.putExtra("url",HttpTools.SYSTEM_MSG_INFO + "?token=" + UserLoginInfo.getUserLoginInfoInstance().getUserToken()+"&id=" + msgInfo.getId());
            intent.putExtra("title",msgInfo.getMsg_title());
            startActivity(intent);
        });
        mPullRecyclerView.setAdapter(mAdapter);

        // 设置下拉刷新的旋转圆圈的颜色
        mPullRecyclerView.setColorSchemeResources(R.color.appBlue);
        // 开启下拉刷新，默认即为true，可不用设置
        mPullRecyclerView.enablePullRefresh(true);
        // 开启数据全部加载完成时的底部提示，默认为false
        mPullRecyclerView.enableLoadDoneTip(true, R.string.load_done_tip);

        //刷新监听
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                // 下拉刷新网络请求
                mPullRecyclerView.enableLoadMore(false);
                Callback.Cancelable doawCallBack = App.getApp().getHttpTools().SystemMessageList("1", "10", CallBackDown);
                RequestTools.addNewRequest(SysteMessageListActivity.class.getName(), doawCallBack);
            }

            @Override
            public void onLoadMore() {
                Callback.Cancelable downCallBack = App.getApp().getHttpTools().SystemMessageList("" + pageGlobal, "10", callBackUp);
                RequestTools.addNewRequest(SysteMessageListActivity.class.getName(), downCallBack);
            }
        });
        mPullRecyclerView.postRefreshing();
        // 通过adapter设置item的点击事件
    }

    @OnClick(R.id.requery_data_tv)
    void onClick() {
        normalLayout();
        mPullRecyclerView.autoRefresh();
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    @Override
    public void setBackButtonFinish() {
        if (ivBack != null) {
            ivBack.setOnClickListener(v -> finish());
        }
    }

    private void noDataLayout() {
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    private void netErrorLayout() {
        if (mNetErrorLayout.getVisibility() == View.GONE) {
            mNetErrorLayout.setVisibility(View.VISIBLE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.GONE);
        }
    }

    private void normalLayout() {
        if (mNullDataLayout.getVisibility() == View.VISIBLE || mNetErrorLayout.getVisibility() == View.VISIBLE) {
            mNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    //下拉获取信息
    RequestCallBack<String> CallBackDown = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                //json解析
                SystemMessageListModel messageListModel = JSON.parseObject(result, SystemMessageListModel.class);
                //有数据
                if (messageListModel != null) {
                    if (messageListModel.getStatus() == 1) {
                        int pageSize = messageListModel.getData().getList().size();
                        if (pageSize > 0) {
                            normalLayout();
                            //清除原数据,加载新数据,上拉加载
                            mDataSize = 0;
                            if (pageSize >= 10) {
                                mPullRecyclerView.enableLoadMore(true);
                            }
                            mDataSize += pageSize;
                            //重置
                            pageGlobal = 2;
                            mAdapter.clear();
                            mAdapter.addAll(messageListModel.getData().getList());
                        } else if (mDataSize == 0) {
                            noDataLayout();
                        }
                    } else {
                        //为空显示空页面
                        if (mDataSize == 0) {
                            noDataLayout();
                            mNullDataWarningTv.setText("暂无消息");
                        } else {
                            ToastUtils.showLong(messageListModel.getInfo());
                        }
                    }
                } else {
                    showErrorToast("解析出错,请重试");
                }
            } catch (Exception ex) {
                showErrorToast("服务端数据异常");
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            if (mDataSize == 0) {
                netErrorLayout();
            } else {
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            }
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.stopRefresh();
            mPullRecyclerView.stopLoadMore();
        }
    };

    //上拉更新信息
    RequestCallBack<String> callBackUp = new RequestCallBack<String>() {

        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                //json解析
                SystemMessageListModel messageListModel = JSON.parseObject(result, SystemMessageListModel.class);
                if (messageListModel != null) {
                    //有数据
                    if (messageListModel.getStatus() == 1) {
                        List<SystemMessageListModel.DataBean.ListBean> datas = messageListModel.getData().getList();
                        int pageSize = 0;
                        if (datas != null) {
                            pageSize = datas.size();
                            if (pageSize > 10) {
                                pageGlobal++;
                            } else {
                                mPullRecyclerView.enableLoadMore(false);
                            }
                            mDataSize += datas.size();
                            mAdapter.addAll(datas);
                        } else {
                            mPullRecyclerView.enableLoadMore(false);
                        }
                    } else {
                        mPullRecyclerView.enableLoadMore(false);
                    }
                } else {
                    showErrorToast("解析出错,请重试");
                }
            } catch (Exception ex) {
                showErrorToast("服务端数据异常");
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            netErrorLayout();
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.stopLoadMore();
        }
    };

    @Override
    protected void onDestroy() {
        // 清空请求
        RequestTools.removeRequest(SysteMessageListActivity.class.getName());
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }
}
